{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from knn import autoNorm, classify0"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "读取文本数据文件，转化为合适的数据类型。注意，这里使用了`np.loadtxt`函数对数据文件读取，代码更精简。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 从文件读取数据，转化为适合处理的数据类型\n",
    "def file2matrix(filename):\n",
    "    dataSet = np.loadtxt(filename,delimiter='\\t')\n",
    "    m,n = dataSet.shape\n",
    "    dataMat = dataSet[:,0:3]\n",
    "    classLabelVector = np.array(dataSet[:,-1],dtype=int)\n",
    "    return dataMat, classLabelVector"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "使用约会网站数据(`datingTestSet2.txt`)对分类器进行训练和测试，并计算错误率。这里一共有1000个样本，取900个用于训练分类器，另外100个用于测试分类器，并计算错误率。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "the total error rate is :0.05\n"
     ]
    }
   ],
   "source": [
    "# 约会测试函数\n",
    "def datingClassTest():\n",
    "    # 设定用于测试的数据量，这里取10%\n",
    "    hoRatio = 0.1\n",
    "\n",
    "    # 从文本数据获取数据集和标签集\n",
    "    datingDataMat, datingLables = file2matrix('data/datingTestSet2.txt')\n",
    "    # 对数据集的特征数据进行归一化处理\n",
    "    normMat,_,_ = autoNorm(datingDataMat)\n",
    "    # 计算用于测试的样本数量\n",
    "    m =datingDataMat.shape[0]\n",
    "    \n",
    "    numTestVecs = int(m*hoRatio)\n",
    "    # 初始化预测错误的样本个数\n",
    "    errorCount = 0\n",
    "    for i in range(numTestVecs):\n",
    "        ret=classify0(normMat[i,:],normMat[numTestVecs:m,:],datingLables[numTestVecs:m],3)\n",
    "        if ret != datingLables[i]:\n",
    "            errorCount += 1\n",
    "    errorrate = errorCount/float(numTestVecs)\n",
    "    print(\"the total error rate is :{}\".format(errorrate))\n",
    "\n",
    "datingClassTest()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "分类器的使用，基于上面错误率尚可，我们就可以使用分类器对一个未分类的样本进行分类。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "你可能喜欢这个人： in samll doses\n"
     ]
    }
   ],
   "source": [
    "# 约会预测函数\n",
    "def classifyPerson():\n",
    "    resultList=['not at all', 'in samll doses', 'in large doses']\n",
    "    # 输入人员信息\n",
    "    ffMiles = float(input(\"每年飞行里程数：\")) # 10000\n",
    "    percentTats = float(input('玩游戏所耗时间百分比：')) # 10\n",
    "    iceCream = float(input(\"每周所吃冰激凌数量：\")) # 0.5\n",
    "    # 从文本数据获取数据集和标签集\n",
    "    datingDataMat, datingLables = file2matrix('data/datingTestSet2.txt')\n",
    "    # 对数据集的特征数据进行归一化处理\n",
    "    normMat,ranges,minVals = autoNorm(datingDataMat)\n",
    "    # 构造输入数据\n",
    "    inAarr = np.array([ffMiles,percentTats,iceCream])    \n",
    "    # 归一化处理\n",
    "    testVec = (inAarr-minVals)/ranges \n",
    "    result = classify0(testVec,normMat,datingLables,3)\n",
    "    print(\"你可能喜欢这个人：\",resultList[result -1])\n",
    "\n",
    "classifyPerson()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "da",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
